<template>
	<view class="pmain">
		<view v-if="depth!=null">
			<view class="item">
				<text class="price">价格</text>
				<text class="num">数量</text>
			</view>
			<view class="uni-column" style="flex-direction: column-reverse;">
				<view class="item" v-for="(item,index) in depth.asks" :key="index">
					<text class="price" style="color: #FD5050;">{{item[0]}}</text>
					<text class="num">{{item[1]}}</text>
				</view>

				<!-- <view class="bg buybg" style="width: 50%;"></view> -->
			</view>
			<view class="current-price" v-if="ticker!=null">
				<view :class="ticker.last>preTicker.last?up:down">{{ticker.last}}</view>
			</view>
			<view class="uni-column">
				<view class="item" v-for="(item,index2) in depth.bids" :key="item[0]">
					<text class="price" style="color: #00DE00;">{{item[0]}}</text>
					<text class="num">{{item[1]}}</text>
				</view>
				<!-- <view class="bg sellbg" style="width: 80%;"></view> -->
			</view>
		</view>
		<!-- <view class="depth uni-thinner-border " @click="depthClick">
			<view class="uni-h6">深度{{depthValue}}</view>
			<view class="popover-wrap" v-show="popoverVisible">
				<view class="kailong"></view>
				<view class="popover uni-thinner-border">
					<view class="item uni-divider" @click="depthChange(1)">1</view>
					<view class="item uni-divider" @click="depthChange(2)">2</view>
					<view class="item uni-divider" @click="depthChange(3)">3</view>
					<view class="item uni-divider" @click="depthChange(4)">4</view>
				</view>
			</view>
		</view> -->

	</view>
</template>

<script>
	var _self
	export default {
		data: function() {
			return {
				testdata: 'hello',
				popoverVisible: false,
				depthValue: 1,
				ticker: null,
				preTicker: null,
				item: Object,
				depth: null,
				freshTimer: null,
				socketOpen: false,
				down: 'uni-h5 uni-bold uni-down usdt',
				up: 'uni-h5 uni-bold uni-up usdt',
				socketTask: null
			}
		},
		mounted() {
			_self = this
			this.fresh()
			uni.$on("positionFresh", this.fresh)
			uni.$on('update', function(data) {
				console.log('监听到事件来自 update ，携带参数 msg 为：' + data.msg);
			})
		},

		computed: {},
		methods: {
			depthClick(e) {
				this.popoverVisible = !this.popoverVisible;
			},
			depthChange(e) {
				this.depthValue = e;
				this.$emit('depthChange', e);
			},

			sendSocketMessage(subscribe, socketToken, tryTimes) {
				console.log('socket status is and try times is  ' + tryTimes)
				console.log(_self.getWSStatus())
				if (tryTimes > 0) {
					if (tryTimes == 5) {
						_self.cleanWSStatus()
					}
					if (_self.getWSStatus() == 'onSocketOpen'||_self.getWSStatus()=='connectSocket') {
						console.log('subscribe on socket open')
						console.log(subscribe)
						uni.sendSocketMessage({
							data: JSON.stringify(subscribe),
							success() {
								console.log('send success')
							},
							fail(e) {
								console.log('send error')
								console.log(e)
								if (e.errMsg == 'sendSocketMessage:fail WebSocket is not connected ') {
									console.log('not connected')
									_self.cleanWSStatus()
									_self.sendSocketMessage(subscribe, socketToken, 10)
								}
							}
						});
					} else {
						_self.wsConnect(socketToken)
						setTimeout(function() {
							_self.sendSocketMessage(subscribe, socketToken, tryTimes - 1);
						}, 3000);

					}
				}

			},

			getUserToken() {
				console.log("get user Info")
				uni.request({
					url: this.api + '/users/info',
					method: 'GET',
					header: {
						"Authorization": "Bearer " + this.getToken()
					},
					success: res => {
						uni.setStorageSync("XSOCKETTOKEN", res.data.data.socketToken)
						_self.pullDepthData()
					}
				});
			},
			pullDepthAndTickerData() {
				let socketToken = uni.getStorageSync("XSOCKETTOKEN")
				if (socketToken == null) {
					_self.getUserToken();
				} else {
					console.log('token is ' + JSON.stringify(socketToken))
					let subscribe = {
						op: 'subscribe',
						args: ["futures/ticker:" + _self.getDefaultContract().instrument_id, "futures/depth5:" + _self.getDefaultContract()
							.instrument_id
						]
					}
					_self.sendSocketMessage(subscribe, socketToken, 10)
					uni.onSocketMessage(function(res) {
						console.log('onSocketMessage')
						// console.log(res)
						var jsonObj = JSON.parse(res.data);
						if (jsonObj.table == 'futures/ticker') {
							let tempTicker = jsonObj.data[0]
							let instrument = tempTicker.instrument_id
							if (instrument == _self.getDefaultContract().instrument_id) {
								if (_self.ticker == null) {
									_self.ticker = tempTicker
								}
								if (_self.preTicker == null) {
									_self.preTicker = tempTicker
								}
								if (_self.ticker.last != tempTicker.last) {
									_self.preTicker = _self.ticker
									_self.ticker = tempTicker
								}
							} else {
								let unsubscribe = {
									op: 'unsubscribe',
									args: ["futures/ticker:" + instrument]
								}
								_self.sendSocketMessage(unsubscribe, socketToken, 3)
							}


						} else if (jsonObj.table == 'futures/depth5') {
							let instrument = jsonObj.data[0].instrument_id
							if (instrument == _self.getDefaultContract().instrument_id) {
								_self.depth = jsonObj.data[0]
							} else {
								let unsubscribe = {
									op: 'unsubscribe',
									args: ["futures/depth5:" + instrument]
								}
								_self.sendSocketMessage(unsubscribe, socketToken, 3)
							}
						}

						console.log(_self.ticker)
					});

				}

			},
			fresh: function() {
				console.log("fresh ticker depth in position")
				if (_self.socketTask != null) {
					_self.socketTask.close()
				}
                
				this.requestTicker()
				this.requestDepth()
				// this.cleanWSStatus()
				// this.pullDepthAndTickerData()
			},

			requestTicker() {
				uni.request({
					url: this.api + '/apis/okex/unauth?simpleUrl=/api/futures/v3/instruments/' + this.getDefaultContract().instrument_id +
						'/ticker',
					method: 'GET',
					success: res => {
						console.log('getticker resp:')
						console.log(res.data.data)
						let tempTicker = res.data.data
						if (this.ticker == null) {
							this.ticker = tempTicker
						}
						if (this.preTicker == null) {
							this.preTicker = tempTicker
						}
						if (this.ticker.last != tempTicker.last) {
							this.preTicker = this.ticker
							this.ticker = tempTicker
						}
					}
				});

			},
			requestDepth() {
				console.log("get depth")
				uni.request({
					url: this.api + '/apis/okex/unauth?simpleUrl=/api/futures/v3/instruments/' + this.getDefaultContract().instrument_id +
						'/book?size=5&depth=0.1',
					method: 'GET',
					success: res => {
						console.log('getDepth resps:')
						console.log(res.data.data)
						let tempDepth = res.data.data
						// tempDepth.asks.reverse()
						this.depth = tempDepth
					}
				});
			}
		}
	}
</script>

<style scoped>
	.pmain {
		width: 100%;
		height: 600upx;
		position: relative;
		justify-content: space-between;
		text-align: left;
	}

	.pmain .item {
		position: relative;
		width: 100%;
		display: flex;
		font-size: 24upx;
	}

	.pmain .item .bg {
		height: 100%;
		position: absolute;
		top: 0;
		right: 0;
		z-index: -9999;
	}

	.pmain .item .buybg {
		background: #fdf4f7;
	}

	.pmain .item .sellbg {
		background: #f0faf9;
	}

	.pmain .item .price {
		display: block;
		width: 50%;
		text-align: left;
	}

	.position .item .num {
		display: block;
		width: 50%;
		text-align: right;
		padding-right: 10upx;
	}

	.pmain .current-price {
		margin: 10upx 0;
	}

	.pmain .current-price .usdt {}

	.pmain .depth {
		position: relative;
		margin-top: 10upx;
		margin-right: 10upx;
	}

	.pmain .depth .uni-h6 {
		text-align: center;
		height: 60upx;
		line-height: 60upx;
	}

	.pmain .depth .popover {
		position: absolute;
		top: 80upx;
		width: 100%;
		z-index: 9999999999;
		background: #ffffff;
		display: inline-block;
		border-radius: 20px;
	}

	.pmain .depth .popover .item {
		width: 100%;
		height: 60upx;
		line-height: 60upx;
		display: block;
		text-align: center;
	}

	.pmain .depth .kailong {
		position: absolute;
		left: 50%;
		top: 74upx;
		transform: translate(-50%, -50%);
		max-width: 50%;
		width: 0;
		height: 0;
		border-right: 20px solid transparent;
		border-left: 20px solid transparent;
		border-bottom: 20px solid #E0E0E0;
	}

	.popover-wrap .uni-thinner-border:before {
		border-radius: 15px !important;
	}
</style>
